<template>
  <view class="booklist">
    <!-- 搜索框 -->
    <view class="booklist__search">
      <view class="booklist__search-inner">
        <text class="booklist__search-icon iconfont icon-sousuo" />
        <input
          type="text"
          :value="keyword"
          placeholder="书籍名称、作者"
          confirm-type="search"
          placeholder-class="booklist__search-input-placeholder"
          class="booklist__search-input"
          @input="handleInputChange"
          @confirm="handleInputConfirm"
        />
        <text
          v-if="keyword.length > 0"
          class="booklist__search-icon iconfont icon-circle-close"
          @click="handleInputClose"
        />
      </view>
    </view>
    <!-- 书籍列表 -->
    <view class="booklist__shelves">
      <view class="booklist__books">
        <view
          v-for="book in list"
          :key="book._id"
          :class="['booklist__book-item', { shake: removing }]"
          @longtap="handleLongTap"
          @click="() => handleClick(book)"
        >
          <image class="booklist__book-image" :src="book.img_url" />
          <view v-if="book.sign === 'update'" class="booklist__sign-update" />
          <view v-if="book.sign === 'over'" class="booklist__sign-over" />
          <i
            v-if="removing"
            class="iconfont icon-circle-close"
            @click="() => handleRemove(book)"
          />
        </view>
        <!-- 添加按钮 -->
        <view
          class="booklist__book-item booklist__add"
          @click="gotoClassifyPage"
        >
          <text class="booklist__add-icon iconfont icon-add"></text>
        </view>
      </view>
    </view>
    <no-data
      v-if="list.length === 0"
      text="这里空空如也，快去阅读吧~"
      comp-style="margin-top: 30rpx"
    />
  </view>
</template>

<script>
import { mapGetters } from 'vuex';
import NoData from '@/components/NoData';

export default {
  components: {
    NoData,
  },

  data() {
    return {
      keyword: '',
      list: [],
      rawList: [],
      lock: false, // 区分点击事件和长按事件
      removing: false, // 是否处于删除书籍的状态
    };
  },

  computed: {
    ...mapGetters(['hasLogin']),
  },

  methods: {
    fetchMyBookList() {
      // 判断是否已经登录
      if (this.hasLogin) {
        this.$http({
          method: 'GET',
          url: '/api/front/booklist',
          needAuth: true,
          errorText: '获取阅读记录失败',
        }).then((res) => {
          if (res.ok) {
            this.rawList = this.formatBookList(res.data.books);
            this.list = [...this.rawList];
          }
        });
      } else {
        // 未登录获取存储在本地里的记录
        const localReadRecords = uni.getStorageSync('readRecords');
        this.rawList = this.formatBookList(localReadRecords || []);
        this.list = [...this.rawList];
      }
    },

    // 格式化和排序
    formatBookList(books = []) {
      const result = [];
      for (let i = 0; i < books.length; i++) {
        const item = books[i];
        // 当书籍不存在则跳过
        if (!item.bookid) continue;
        const { newest_chapter = 1, update_status = '连载中' } = item.bookid;
        // 计算书籍标签
        let sign = '';
        if (item.read) {
          if (item.read.num < newest_chapter) {
            sign = 'update';
          } else if (
            item.read.num === newest_chapter &&
            update_status === '已完结'
          ) {
            sign = 'over';
          }
        }
        // 添加到需要展示的数组中
        result.push({
          bookid: item.bookid._id,
          read_num: item.read ? item.read.num || 0 : 0,
          read_top: item.read ? item.read.top || 0 : 0,
          read_scroll: item.read ? item.read.scroll || 0 : 0,
          rss: item.rss,
          time: item.time,
          name: item.bookid.name,
          author: item.bookid.author,
          img_url: item.bookid.img_url,
          sign,
        });
      }
      // 根据time排序
      result.sort((book1, book2) => {
        if (book2.time instanceof Date && book1.time instanceof Date) {
          return book2.time.getTime() - book1.time.getTime();
        } else {
          return (
            new Date(book2.time).getTime() - new Date(book1.time).getTime()
          );
        }
      });
      return result;
    },

    gotoClassifyPage() {
      uni.navigateTo({ url: '/pages/classify/index?index=0' });
    },

    handleInputChange(event) {
      this.keyword = event.detail.value;
    },

    handleInputConfirm(event) {
      // 禁止关键字为空的搜索
      if (!event.detail.value) {
        return false;
      }
      this.list = this.setDataFromRawList();
    },

    handleInputClose() {
      this.keyword = '';
      this.list = [...this.rawList];
    },

    // 根据关键字检索列表
    setDataFromRawList() {
      this.list = this.rawList.filter((item) => {
        return (
          item.name.indexOf(this.keyword) > -1 ||
          item.author.indexOf(this.keyword) > -1
        );
      });
    },

    handleClick(item) {
      if (this.lock) return;
      if (this.removing) {
        this.removing = false;
        return;
      }
      uni.navigateTo({
        url: `/pages/reader/index?book=${item.bookid}`,
      });
    },

    handleLongTap() {
      this.lock = true;
      this.removing = true;
      setTimeout(() => {
        this.lock = false;
      }, 500);
    },

    handleRemove(target) {
      if (this.hasLogin) {
        this.$http({
          method: 'POST',
          url: '/api/front/booklist/remove',
          data: {
            id: target.bookid,
          },
          needAuth: true,
          errorText: '删除书籍失败',
        }).then((res) => {
          if (res.ok) {
            this.list = this.list.filter(
              (item) => item.bookid !== target.bookid
            );
          }
        });
      } else {
        this.list = this.list.filter((item) => item.bookid !== target.bookid);
        const localReadRecords = uni.getStorageSync('readRecords');
        uni.setStorageSync(
          'readRecords',
          localReadRecords.filter((item) => item._id !== target.bookid)
        );
      }
    },
  },

  onShow() {
    this.fetchMyBookList();
  },
};
</script>

<style lang="scss">
.booklist {
  &__search {
    padding: 0 $page-row-spacing;
    margin-top: 30rpx;

    &-inner {
      position: relative;
      color: $font-color-search-text;
      width: 100%;
      height: 72rpx;
      border-radius: 36rpx;
      font-size: 32rpx;
      background: #f1f2f6;
      background-clip: content-box;
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-start;
      align-items: center;
      margin-bottom: $page-row-spacing;
    }

    &-input {
      display: block;
      height: 100%;

      &-placeholder {
        font-size: 28rpx;
        color: $font-color-search-placeholder;
      }
    }

    .icon-sousuo {
      display: inline-block;
      width: 36rpx;
      height: 36rpx;
      font-size: 18px;
      margin-left: 24rpx;
      margin-right: 18rpx;
    }

    .icon-circle-close {
      position: absolute;
      width: 44rpx;
      height: 44rpx;
      padding: 4rpx;
      top: 50%;
      margin-top: -22rpx;
      right: 24rpx;
      z-index: 2;
    }
  }

  &__shelves {
    height: 100%;
    background: url('../../static/booklist/shalves.png') no-repeat;
    background-repeat: repeat-y;
    background-color: #ffffff;
    background-size: 100% auto;
  }

  &__books {
    display: -webkit-flex;
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    align-items: flex-start;
    padding: 0 60rpx;
  }

  &__book-item {
    width: 180rpx;
    margin-right: 45rpx;
    margin-top: 12rpx;
    margin-bottom: 64rpx;
    position: relative;

    &:nth-child(3n + 0) {
      margin-right: 0;
    }

    .icon-circle-close {
      color: #999;
      font-size: 32rpx;
      position: absolute;
      left: -26rpx;
      top: -26rpx;
      padding: 12rpx;
    }

    &.shake {
      animation-duration: 0.5s;
      animation-fill-mode: both;
      animation-name: shake;
    }
  }

  &__book-image {
    display: inline-block;
    width: 100%;
    height: 240rpx;
    border-radius: 6rpx;
    box-shadow: 4rpx 4rpx 2rpx #f5f7f6;
    position: relative;
    top: 1rpx;
  }

  &__sign-update {
    width: 50rpx;
    height: 30rpx;
    background: linear-gradient(-45deg, #d2723f 0%, #e81210 100%);
    position: absolute;
    top: 0;
    right: 0;
    font-size: 20rpx;
    color: #ffffff;
    text-align: center;
    line-height: 30rpx;
    border-bottom-left-radius: 6rpx;
    border-top-right-radius: 6rpx;
    opacity: 0.8;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;

    &::after {
      content: '更新';
      font-size: 14px;
      transform: scale(0.68);
      display: block;
      white-space: nowrap;
      line-height: 1;
    }
  }

  &__sign-over {
    width: 50rpx;
    height: 30rpx;
    background: linear-gradient(-45deg, #ffb37d 0%, #d67f1e 100%);
    position: absolute;
    top: 0;
    right: 0;
    font-size: 20rpx;
    color: #ffffff;
    text-align: center;
    line-height: 30rpx;
    border-bottom-left-radius: 6rpx;
    border-top-right-radius: 6rpx;
    opacity: 0.8;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;

    &::after {
      content: '读完';
      font-size: 14px;
      transform: scale(0.68);
      display: block;
      white-space: nowrap;
      line-height: 1;
    }
  }

  &__add {
    position: relative;
    box-sizing: border-box;
    background-color: #dddddd;
    height: 240rpx;
    border-radius: 6rpx;
    top: 1rpx;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
  }

  &__add-icon {
    font-size: 32rpx;
  }
}

@keyframes shake {
  from,
  to {
    transform: translate3d(0, 0, 0);
  }
  10%,
  40%,
  70% {
    transform: translate3d(-10rpx, 0, 0);
  }
  25%,
  55%,
  85% {
    transform: translate3d(10rpx, 0, 0);
  }
}
</style>
